<template>
    <div class="login-container">
      <el-form 
        :model="loginForm" 
        :rules="rules" 
        ref="loginFormRef" 
        label-width="80px" 
        class="login-form"
      >
        <h2 class="login-title">用户登录</h2>
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            placeholder="请输入密码" 
            show-password
          ></el-input>
        </el-form-item>
        
        <div class="button-group">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="resetForm">取消</el-button>
        </div>
      </el-form>
    </div>
  </template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { login } from '@/api/login';
import { useRouter } from 'vue-router'
const loginFormRef = ref(null);

const loginForm = ref({
  username: '',
  password: ''
});

const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
  ]
});

let router = useRouter()
const submitForm = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
        const res = await login(loginForm.value)
        console.log(loginForm.value)
        // 在这里添加你的登录逻辑
        if (res.code) {
          ElMessage.success('登录成功!');
          localStorage.setItem('loginUser', JSON.stringify(res.data))
          router.push('/')
        } else {
          ElMessage.error(res.msg);
        }
      

    } else {
      ElMessage.error('表单验证失败!');
      return false;
    }
  });
};

const resetForm = () => {
  loginFormRef.value.resetFields();
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-form {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 400px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.el-button {
  width: 45%;
}
</style>